/**
 * Copyright (C) 2018 - 2020 https://github.com/LeeYan9
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.async;

import com.alibaba.fastjson.JSONObject;
import com.bifrost.constant.MerchantConfigurationType;
import com.bifrost.entity.Customer;
import com.bifrost.entity.MerchantConfiguration;
import com.bifrost.entity.MerchantStore;
import com.bifrost.model.TemplateData;
import com.bifrost.model.WxTemplateModel;
import com.bifrost.repository.MerchantConfigurationRepository;
import com.bifrost.repository.MerchantStoreRepository;
import com.bifrost.util.HttpClientUtil;
import com.bifrost.wechat.entity.WechatAccount;
import com.bifrost.wechat.service.WechatAccountService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author Lee
 * Create Class on 2018/8/22
 * @com.bifrost.async
 * @wechat-mall
 */
@Component
@Slf4j
public class CustomerAsync {

    @Autowired
    MerchantConfigurationRepository configurationRepository;
    @Autowired
    MerchantStoreRepository merchantStoreRepository;
    @Autowired
    WechatAccountService accountService;

    @Async
    public void sendRegisterTemplate(Long stroeId, Customer user, String bonusPoints, String format) {
        List<MerchantConfiguration> list = configurationRepository.findByMerchantStoreAndTypeAndKey(stroeId, MerchantConfigurationType.MESSAGE.name(), "REGISTER");
        // log.error(String.format("门店：[%s] ， 用户注册成功 ID[%s]，消息模板发送失败  没有匹配的门店消息模板",stroeId,user.getCustomerId()));

        MerchantStore store = merchantStoreRepository.findOne(stroeId);

        HashMap<String, TemplateData> map = new HashMap<>();
        map.put("first",new TemplateData("亲爱的会员,你的会员卡有新积分到账"));
        map.put("keyword1",new TemplateData(user.getLoyaltyCard()));
        map.put("keyword2",new TemplateData(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
        map.put("keyword3",new TemplateData("会员积分"));
        map.put("keyword4",new TemplateData(bonusPoints+" 积分"));
        map.put("keyword5",new TemplateData(user.getBonusPoints().add(new BigInteger(bonusPoints))+" 积分"));
        map.put("remark",new TemplateData(store.getStoreName()));

        WxTemplateModel templateModel = new WxTemplateModel();
        templateModel.setData(map);
        templateModel.setTemplate_id(list.get(0).getValue());
        templateModel.setTouser(user.getOpenId());
        templateModel.setTopcolor("#FF0000");
        String parm= JSONObject.toJSONString(templateModel);
        String url = String.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s",getAccessToken(accountService.getAccount(store.getMerchantId())));
        String json= HttpClientUtil.doPostJson1(url,parm,null);
        log.debug("微信返回模板请求信息:"+json);
        if (!json.contains("errcode")){
            log.debug("积分消息模板推送失败!,用户ID:["+user.getCustomerId()+"]。微信返回json:"+json);
        }
        JSONObject j=JSONObject.parseObject(json);
        if (j.getString("errcode").equals("0")){
            log.debug("积分消息模板推送成功!,用户ID:["+user.getCustomerId()+"]。");
        }else{
            log.debug("积分消息模板推送失败!,用户ID:["+user.getCustomerId()+"]。微信返回json:"+json);
        }

    }

    public static String getAccessToken(WechatAccount account){
        Assert.notNull(account,"不存在门店参数");
        Map<String,String> map=new TreeMap<>();
        map.put("grant_type","client_credential");
        map.put("appid",account.getAppId());
        map.put("secret",account.getAppSecret());

        String c=HttpClientUtil.doGet("https://api.weixin.qq.com/cgi-bin/token",map);
        String access_token="";
        if (c.contains("access_token")){
            JSONObject jsonObject=JSONObject.parseObject(c);
            access_token=jsonObject.getString("access_token");
        }
        log.debug("微信返回access_token:"+access_token);
        return access_token;
    }
}
